<template>
  <div class="view-article">
    <div
      class="head bg"
      :style="{
        background: 'url(\'' + article.cover_picture + '\')',
      }"
    >
      <!-- 文章封面 -->
      <div class="cover-picture" />
      <!-- 文章信息 -->
      <div class="article-info">
        <!--文章标题 -->
        <h1>{{ article.title }}</h1>
        <!-- 文章信息提示 -->
        <div class="article-info-tip" ref="tip">
          <span class="time">
            <i class="el-icon-time"></i> 发布于{{
              String(article.created_time).substring(0, 10)
            }}
            |
          </span>
          <span v-show="article.is_recommend"
            ><i class="el-icon-star-on"></i> 推荐 |
          </span>
          <span class="category"
            ><i class="el-icon-menu"></i> {{ article.category_name }} |
          </span>
          <span class="comment"
            ><i class="el-icon-s-comment"></i> {{ currentMessagesTotal }} |
          </span>
          <span class="visitCount"
            ><i class="el-icon-view"></i> {{ article.visit_count }}
          </span>
        </div>
      </div>
    </div>
    <div class="main">
      <layout-col>
        <!-- 左边区域 -->
        <template #left>
          <!-- 插槽使用: 添加"item"类即可产生卡片样式, item之外可以再自定义别的样式类 -->
          <div class="item left-height ql-snow">
            <div
              ref="aContent"
              id="aContent"
              class="article-conntent ql-editor"
              v-html="article.content"
            ></div>
            <!-- 评论 -->
            <div class="comment">
              <div class="comment-input">
                <textarea
                  v-model.trim="newContent"
                  @input="handleInput"
                  :maxlength="handleStopWrite()"
                  placeholder="评论一下"
                ></textarea>
                <button class="comment-btn" @click="handleSubmit">发表</button>
              </div>
              <div class="input-tip">
                {{ '字数：' + inputLength + '/' + maxInputLength }}
              </div>
              <div class="comment-content">
                <ul>
                  <li
                    v-for="(item, index) in currentMessagesAndUserInfo"
                    :key="index"
                  >
                    <img :src="item.avatar" alt="" />
                    <div class="info">
                      <span class="user-item">
                        {{ item.nickname + ' ： ' }}
                      </span>
                      <span>{{ item.created_time }}</span>
                      <p class="comment-item">
                        {{ item.content }}
                      </p>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </template>
        <!-- 右边区域 -->
        <template #right>
          <div class="item">
            <div class="dictionary">
              <span class="dictionary-name">大纲</span>
              <ul>
                <li v-for="(item1, index1) in dirTree" :key="index1">
                  <a :href="'#' + item1.link" class="first-title">{{
                    item1.label
                  }}</a>
                  <ul>
                    <li v-for="(item2, index2) in item1.children" :key="index2">
                      <a :href="'#' + item2.link" class="second-title">{{
                        item2.label
                      }}</a>
                      <ul>
                        <li
                          v-for="(item3, index3) in item2.children"
                          :key="index3"
                        >
                          <a :href="'#' + item3.link" class="third-title">{{
                            item3.label
                          }}</a>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </li>
              </ul>
            </div>
          </div>
        </template>
      </layout-col>
    </div>
  </div>
</template>

<script>
import LayoutCol from '@/components/LayoutCol.vue'
export default {
  name: 'HomeViewArticle',
  components: { LayoutCol },
  data() {
    return {
      article: {},
      currentCategory: '',
      currentMessagesAndUserInfo: [],
      currentMessagesTotal: 0,
      currentUserId: '',
      newContent: '',
      inputLength: 0,
      maxInputLength: 100,
      dirTree: [],
    }
  },
  methods: {
    getArticle() {
      // 当前文章的id this.$route.query.id
      this.$http.get(`/articles?id=${this.$route.query.id}`).then((res) => {
        this.article = res.result[0]
        this.getCurrentMessagesAndUserInfo(this.article)
      })
    },
    getCurrentMessagesAndUserInfo(article) {
      this.$http
        .get(`/comments/userinfo/?article_id=${article.id}`)
        .then((res) => {
          this.currentMessagesTotal = res.result.total
          this.currentMessagesAndUserInfo = res.result.msg_userinfo.reverse()
        })
    },
    handleSubmit() {
      this.$http.get('/login/getinfo').then((res) => {
        // console.log('loginInfo', res)
        if (res.code == 0) {
          this.currentUserId = res.result.id
        } else {
          this.$message({
            type: 'error',
            message: '未登录，请先登录再评论!',
          })
          return
        }
        let newContent = {
          content: this.newContent,
          user_id: this.currentUserId,
          article_id: this.article.id,
        }
        // console.log(newContent)
        if (newContent.content == '') {
          this.$message({
            type: 'error',
            message: '输入为空，请重新输入!',
          })
          return
        }
        this.$http.post(`/comments/`, newContent).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '评论成功!',
            })
            this.newContent = ''
            this.inputLength = 0
            this.getCurrentMessagesAndUserInfo(this.article)
          } else {
            this.$message({
              type: 'error',
              message: '评论失败!',
            })
          }
        })
      })
    },
    getCurrentLoginUser() {
      // GET /login/getinfo
      this.$http.get('/login/getinfo').then((res) => {
        // console.log('loginInfo', res)
        // 优化点,需要判断登录
        if (res.code == 0) {
          this.currentUserId = res.result.id
        }
      })
    },
    handleInput() {
      this.inputLength = this.newContent.length
    },
    handleStopWrite() {
      if (this.inputLength >= this.maxInputLength) {
        return 0
      } else {
        return 100
      }
    },
    toTree(data) {
      // 删除 所有 children,以防止多次调用
      data.forEach(function (item) {
        delete item.children
      })

      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {}
      data.forEach(function (item) {
        map[item.id] = item
      })
      var val = []
      data.forEach(function (item) {
        // 以当前遍历项的pid,去map对象中找到索引的id
        var parent = map[item.p_id]
        // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
          ;(parent.children || (parent.children = [])).push(item)
        } else {
          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
          val.push(item)
        }
      })
      return val
    },
    makeDirTree() {
      if (true) {
        this.$nextTick(() => {
          // 定义参与目录生成的标签
          const tocTags = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
          // 目录树结果
          const tocArr = []
          // 获取所有标题标签
          const headDoms = Array.from(this.$refs.aContent.childNodes).filter(
            (item) => tocTags.includes(item.tagName)
          )
          // 遍历标题标签
          headDoms.forEach((item, index, arr) => {
            // 给标题添加id
            item.id = `h-${index + 1}`
            // 获取当前节点前面的节点
            let prevs = arr.filter((i, j) => j < index)
            // 过滤前面的节点为合理节点
            // 如 h3节点前  只能为 h1 h2 h3
            prevs = prevs.filter((i) =>
              tocTags
                .filter(
                  (i, j) => j <= tocTags.findIndex((i) => i == item.tagName)
                )
                .includes(i.tagName)
            )
            // 对前面的节点进行排序，距离自身节点近的排在前面
            // 如 div > p > span > img  当前为img
            // 常规获取节点为 [div,p,span,img]
            // 排序后获取节点为 [img,span,p,div]
            prevs = prevs.sort(
              (a, b) => -a.id.replace('h-', '') - b.id.replace('h-', '')
            )
            // 查询距离自身节点最近的不同于当前标签的节点
            const prev = prevs.find((i) => i.tagName != item.tagName)

            tocArr.push({
              id: index + 1, // 抛出id
              link: 'h-' + (index + 1), // 抛出id
              tag: item.tagName, // 抛出标签名称
              label: item.innerText, // 抛出标题
              p_id:
                item.tagName == 'H1' ? 0 : Number(prev.id.replace('h-', '')), // 抛出父级id
            })
          })

          // 使用上述方法生成树 最后在el-tree的data中使用 tocData即可
          this.dirTree = this.toTree(tocArr)
          // console.log(this.dirTree)
        })
      }
    },
  },
  created() {
    document.documentElement.scrollIntoView({
      block: 'start',
      behavior: 'smooth', // 平滑滚动
    })
    // 当前文章的id this.$route.query.id
    this.$http
      .put(`/articles/view_num?id=${this.$route.query.id}`)
      .then((res) => {
        if (res.code == 0) {
          // console.log('文章访问量+1')
        }
      })
    this.getArticle()
    this.getCurrentLoginUser()
  },
  updated() {
    this.makeDirTree()
  },
}
</script>

<style lang="stylus" scoped>
@import '~styles/theme.styl';

.bg
  position relative
  background-repeat: no-repeat !important
  background-size: cover !important
  background-color: #dff6fc !important
  // 背景图片位置固定，猫咪固定在右下
  background-attachment: fixed !important
  background-position: center center !important
.left-height
  .article-conntent
    padding: 20px 30px 20px 30px
.view-article {
  transition: all 0.5s;

  .head {
    // position: relative
    height: 100vh;

    .cover-picture {
      width: 100%;
      height: 100vh;
    }

    .article-info {
      position: relative;
      top: -100vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      background: var(--mask);

      // 文章标题
      h1 {
        font-size: 50px;
        font-family: 'STXinwei','KaiTi', '隶书'
        color: var(--color);
        transition: all 0.5s
      }

      // 文章信息提示
      .article-info-tip {
        width: 40%;
        height: 60px;
        margin: 30px 0 60px 0;
        padding: 0 15px;
        line-height: 60px;
        text-align: center;
        font-size: 20px;
        border-radius: 30px;
        background: var(--transparentDiv);

        p {
          font-weight: bolder;
        }
      }
    }
  }

  .main {
    .comment {
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      // margin: 50px 0 30px 0;

      .comment-input {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: flex-end;
        margin: 0px;
        border-top: 0.1px solid #9aa0a6;
        padding-top: 30px;
        padding-bottom: 30px;

        textarea {
          background-color var(--mask)
          box-sizing: border-box;
          width: 80%;
          height: 200px;
          padding: 10px;
          outline: none;
          border: 0.1px solid #9aa0a6;
          border-radius: 10px;
          margin-right: 10px;
          color: var(--color)
          font-size: 20px;
          resize: none;
        }

        .comment-btn {
          width: 77px;
          height: 40px;
          border: none;
          border-radius: 20px;
          color: #fff;
          font-size: 20px;
          background-color: #0187fb;
          cursor: pointer;
        }
      }

      .input-tip {
        position: relative;
        left: 35px;
      }

      .comment-content {
        li {
          margin: 20px 20px
          display: flex
        }

        img {
          width: 60px;
          height: 60px;
          margin-top: 15px
          border-radius: 30px;
          border: 0.1px solid #9aa0a6;
        }
        .info{
          padding-left:15px;
          }

        .user-item {
          // height: 60px;
          color: var(--color);
          font-weight: bold;
          line-height: 60px;
        }

        .comment-item {
          // float: left
          // display: inline-block
          position: relative;
          top: -10px;
          width: 100%;
          // height: 60px
          color: var(--color);
          word-break: break-all; /* 强制英文单词断行，中文也适用 */
          word-wrap: break-word; /* 自动换行 */
          // line-height: 30px
          // overflow: hidden
        }
      }
    }

    .dictionary {
      width: 100%;
      padding: 10px;

      .dictionary-name {
        display: block;
        text-align: center
        font-size: 40px;
        font-family: 'STXinwei'
        text-decoration: none;
        margin-bottom: 20px;
        color: var(--color);
      }
      .first-title, .second-title, .third-title{
        font-family: 'KaiTi'
        transition: all .5s
      }
      .first-title:hover, .second-title:hover, .third-title:hover{
        color:#ff638a
      }
      .first-title {
        max-size:100%
        overflow: hidden
        font-size: 25px;
        text-decoration: none;
        line-height: 40px;
        font-weight:bold;
        color: #000;
        color: var(--color);
      }

      .second-title {
        max-size:100%
        overflow: hidden
        font-size: 20px;
        text-decoration: none;
        margin-left: 25px;
        line-height: 30px;
        color: #000;
        color: var(--color);
      }

      .third-title {
        max-size:100%
        overflow: hidden
        font-size: 15px;
        text-decoration: none;
        margin-left: 50px;
        line-height: 20px;
        color: #000;
        color: var(--color);
      }
    }
  }
}
</style>
